package networking.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import networking.config.parser.Node;

public class TcpClientServer {

	public static void createClientSocket(Node clientNode, Node serverNode) {
		try {

			Socket clientSocket = new Socket(serverNode.getIp(), serverNode.getPort());
			while (!clientSocket.isConnected()) {
				clientSocket = new Socket(serverNode.getIp(), serverNode.getPort());
			}
			clientNode.setClientSocket(clientSocket);
		} catch (ConnectException e) {
			createClientSocket(clientNode, serverNode);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void createServerSocket(Node serverNode) {
		try {
			serverNode.setServerSocket(new ServerSocket(serverNode.getPort()));
			assert serverNode.getServerSocket().isBound();
			System.out.println("Waiting for the client to connect....");
			serverNode.setServerSocketPerClient(serverNode.getServerSocket().accept());

		} catch (SocketException e) {
			System.out.println("Unable to create the socket! " + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void sendPacket(Socket socket) {

		String message = "Parisa";
		OutputStream out;

		try {
			out = socket.getOutputStream();
			PrintWriter outP = new PrintWriter(out, true);
			outP.print(message);
			System.out.print("Sending string: '" + message + "'\n");
			outP.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void recvPacket(Socket socket) {
		InputStream in;
		try {
			in = socket.getInputStream();
			BufferedReader breader = new BufferedReader(new InputStreamReader(in));
			while (!breader.ready()) {
			}
			System.out.println(breader.readLine());
			breader.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
